package com.app.yc.ifapp;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.app.yc.ifapp.asynctask.WebApiRequest;
import com.app.yc.ifapp.entity.ApiResult;
import com.app.yc.ifapp.entity.Card;
import com.app.yc.ifapp.entity.UserInfo;
import com.app.yc.ifapp.utils.ApiUtils;
import com.app.yc.ifapp.utils.GZipUtils;
import com.app.yc.ifapp.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.NumberFormat;

public class MainActivity extends Activity {

    UserInfo mUserInfo;
    String url;

    TextView tv_user_name;
    TextView tv_user_no;
    TextView tv_user_type;
    TextView tv_card_value;
    TextView tv_card_status;
    TextView tv_card_validity;
    TextView tv_title;
    TextView tv_logout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mUserInfo = getIntent().getParcelableExtra("user");
        url = getIntent().getStringExtra("url");

        initStyles();
        queryPhoto();
        queryCard();
    }

    /**
     * 初始化界面
     */
    private void initStyles() {
        tv_user_name = (TextView) findViewById(R.id.text_user_name);
        tv_user_no = (TextView) findViewById(R.id.text_user_no);
        tv_user_type = (TextView) findViewById(R.id.text_user_type);
        tv_title = (TextView) findViewById(R.id.text_title);
        tv_logout = (TextView) findViewById(R.id.text_logout);
        tv_card_value = (TextView) findViewById(R.id.text_card_value);
        tv_card_status = (TextView) findViewById(R.id.text_card_status);
        tv_card_validity = (TextView) findViewById(R.id.text_card_validity);

        tv_user_name.setText(mUserInfo.getUserName());
        tv_user_no.setText(mUserInfo.getUserNo());
        tv_card_value.setText(R.string.text_sample_decimal);
        tv_card_status.setText(R.string.text_un_know);
        tv_card_validity.setText(R.string.text_un_know);
        tv_logout.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                MainActivity.this.startActivity(intent);

                //清空登录信息
                SharedPreferences sp = getSharedPreferences("login_user",
                        Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sp.edit();
                editor.putString("user_no", StringUtils.EMPTY);
                editor.putString("password", StringUtils.EMPTY);
                editor.putString("url", StringUtils.EMPTY);
                editor.apply();

                finish();
            }
        });

        switch (mUserInfo.getUserType()) {
            case 1:
                tv_user_type.setText("教师");
                break;
            case 2:
                tv_user_type.setText("学生");
                break;
            case 3:
                tv_user_type.setText("家长");
                break;
            default:
                tv_user_type.setText("未知");
                break;
        }

        //智能控制
        TextView tv_intelligent_control = (TextView) findViewById(R.id.text_intelligent_control);
        tv_intelligent_control.setOnClickListener(new TextView.OnClickListener() {

            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, IntelligentControlActivity.class);
                //把附加的数据放到意图当中
                intent.putExtra("user", mUserInfo);
                intent.putExtra("url", url);
                MainActivity.this.startActivity(intent);
            }
        });
        //红外控制
        TextView tv_infrared_control = (TextView) findViewById(R.id.text_infrared_control);
        tv_infrared_control.setOnClickListener(new TextView.OnClickListener() {

            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, InfraredControlActivity.class);
                //把附加的数据放到意图当中
                intent.putExtra("user", mUserInfo);
                intent.putExtra("url", url);
                MainActivity.this.startActivity(intent);
            }
        });


        //获取并缩放右箭头
        Drawable arrow = ContextCompat.getDrawable(this, R.mipmap.right_arrow);
        arrow.setBounds(0, 0, arrow.getIntrinsicWidth() / 3,
                arrow.getIntrinsicHeight() / 3);
        //智能控制图标
        Drawable smart_control = ContextCompat.getDrawable(this, R.mipmap.smart_control);
        smart_control.setBounds(0, 0, smart_control.getIntrinsicWidth() / 2,
                smart_control.getIntrinsicHeight() / 2);
        //红外控制图标
        Drawable ir_control = ContextCompat.getDrawable(this, R.mipmap.ir_control);
        ir_control.setBounds(0, 0, smart_control.getIntrinsicWidth() / 2,
                smart_control.getIntrinsicHeight() / 2);
        //我的智慧校园图标
        Drawable my_smart_school = ContextCompat.getDrawable(this, R.mipmap.ic_launcher);
        my_smart_school.setBounds(0, 0, (int) (my_smart_school.getIntrinsicWidth() * 0.7),
                (int) (my_smart_school.getIntrinsicHeight() * 0.7));
        //设置右箭头
        tv_intelligent_control.setCompoundDrawables(smart_control, null, arrow, null);
        tv_infrared_control.setCompoundDrawables(ir_control, null, arrow, null);
        tv_title.setCompoundDrawables(my_smart_school, null, null, null);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    /*
     * 请求照片信息
     */
    private void queryPhoto() {
        WebApiRequest request = new WebApiRequest();
        request.setAsyncTaskCallBack(new WebApiRequest.AsyncTaskCallBack() {

            @Override
            public void onTaskOver(String result) {

                if (TextUtils.isEmpty(result)) {
                    Toast.makeText(MainActivity.this, R.string.error_api_fail, Toast.LENGTH_SHORT)
                            .show();
                    return;
                }

                String image;

                try {
                    Gson gson = new Gson();
                    ApiResult<String> apiResult = gson.fromJson(result,
                            new TypeToken<ApiResult<String>>() {
                            }.getType());

                    if (apiResult != null && apiResult.getResult()) {
                        image = apiResult.getData();

                        ImageView iv = (ImageView) findViewById(R.id.image_employee_photo);
                        byte[] buffer = GZipUtils.decompressForGzip(image);
                        if (buffer != null && buffer.length > 0) {
                            Bitmap img = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
                            if (img != null) {
                                iv.setImageBitmap(img);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        try {
            //构造请求登录参数
            String params = "?empStrId" + "=" +
                    URLEncoder.encode(mUserInfo.getUserNo(), "UTF-8");
            request.execute(url + ApiUtils.GET_PHOTO + params, StringUtils.EMPTY);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(MainActivity.this, R.string.error_api_fail, Toast.LENGTH_SHORT)
                    .show();
        }
    }

    /*
     * 请求卡片信息
     */
    private void queryCard() {
        WebApiRequest request = new WebApiRequest();
        request.setAsyncTaskCallBack(new WebApiRequest.AsyncTaskCallBack() {

            @Override
            public void onTaskOver(String result) {

                if (TextUtils.isEmpty(result)) {
                    Toast.makeText(MainActivity.this, R.string.error_api_fail, Toast.LENGTH_SHORT)
                            .show();
                    return;
                }

                try {
                    Gson gson = new Gson();
                    ApiResult<Card> apiResult = gson.fromJson(result,
                            new TypeToken<ApiResult<Card>>() {
                            }.getType());

                    if (apiResult != null && apiResult.getResult() && apiResult.getData() != null) {
                        NumberFormat format = NumberFormat.getCurrencyInstance();
                        tv_card_value.setText(format.format(apiResult.getData().getCardValue()
                                .setScale(2, BigDecimal.ROUND_DOWN)));
                        switch (apiResult.getData().getCardStatusId()) {
                            case 1:
                                tv_card_status.setText(R.string.text_card_status_normal);
                                break;
                            case 2:
                                tv_card_status.setText(R.string.text_card_status_lost);
                                break;
                            case 3:
                                tv_card_status.setText(R.string.text_card_status_cancellation);
                                break;
                            case 4:
                                tv_card_status.setText(R.string.text_card_status_cancel);
                                break;
                            default:
                                tv_card_status.setText(R.string.text_un_know);
                                break;
                        }
                        tv_card_validity.setText(apiResult.getData().getValidate());
                    } else {
                        tv_card_value.setText(R.string.text_sample_decimal);
                        tv_card_status.setText(R.string.text_un_know);
                        tv_card_validity.setText(R.string.text_un_know);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        try {
            //构造请求登录参数
            String params = "?empStrId" + "=" +
                    URLEncoder.encode(mUserInfo.getUserNo(), "UTF-8");
            request.execute(url + ApiUtils.GET_CARD + params, StringUtils.EMPTY);
        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(MainActivity.this, R.string.error_api_fail, Toast.LENGTH_SHORT)
                    .show();
        }
    }
}
